package com.khalil.kkadmin.web;

import com.khalil.kkadmin.common.web.RespResult;
import com.khalil.kkadmin.system.dms.DmsDocument;
import com.khalil.kkadmin.system.dms.DmsDocumentService;
import com.khalil.kkadmin.system.dms.FileInfo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("document")
public class DmsDocumentController {

    private final DmsDocumentService dmsDocumentService;

    public DmsDocumentController(DmsDocumentService dmsDocumentService) {
        this.dmsDocumentService = dmsDocumentService;
    }

    @PostMapping("upload")
    public RespResult<List<DmsDocument>> upload(@RequestParam("file") List<MultipartFile> multipartFileList) {
        List<DmsDocument> dmsDocumentInfoList = new ArrayList<>();
        try {
            for (MultipartFile multipartFile : multipartFileList) {
                String originalFilename = multipartFile.getOriginalFilename();
                String extension = FilenameUtils.getExtension(originalFilename);
                String contentType = multipartFile.getContentType();
                InputStream inputStream = multipartFile.getInputStream();
                long fileSize = multipartFile.getSize();
                FileInfo fileInfo = FileInfo.builder().originalFilename(originalFilename).contentType(contentType).size(fileSize).extension(extension).inputStream(inputStream).build();
                DmsDocument upload = dmsDocumentService.upload(fileInfo);
                dmsDocumentInfoList.add(upload);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return RespResult.ok(dmsDocumentInfoList);
    }

    @GetMapping("download")
    public ResponseEntity<InputStreamResource> download(@RequestParam("id") Long id) {
        FileInfo fileInfo = dmsDocumentService.download(id);
        HttpHeaders headers = new HttpHeaders();
        String encodedAttachmentName = URLEncoder.encode(fileInfo.getOriginalFilename(), StandardCharsets.UTF_8);
        headers.add("Content-Disposition", "attachment; filename=" + encodedAttachmentName);

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(fileInfo.getSize())
                .contentType(MediaType.valueOf(fileInfo.getContentType()))
                .body(new InputStreamResource(fileInfo.getInputStream()));
    }
}
